package com.hmjk.health.card;

import org.json.JSONException;
import org.json.JSONObject;

import com.hmjk.health.HealthApp;
import com.hmjk.health.R;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.background.NetService;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.Time;
import android.util.Log;
import android.view.View.OnClickListener;
import android.view.View;
import android.view.Window;

import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;


public class NewDeviceActivity extends Activity implements OnClickListener, TextWatcher{
	private final String TAG = NewDeviceActivity.class.getSimpleName();
	private HealthApp mApp = null;
	private String mDid;
	private EditText mName;
	private EditText mPhone;
	private Button mCommit;
	private String mCommitPhone;
	private String mCommitName;
	private String mCommitTid;
	
	private void logd(String info){
		Log.d(TAG,info);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		logd("onCreate");
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mApp = (HealthApp)getApplication();
		Intent i = getIntent();
		mDid = i.getStringExtra("did");
		
		setContentView(R.layout.add_new_device_activity);
		ImageButton back = (ImageButton)findViewById(R.id.back);
		back.setOnClickListener(this);
		
		mCommit = (Button)findViewById(R.id.commit);
		mCommit.setOnClickListener(this);
		mCommit.setEnabled(false);
		
		mName = (EditText) findViewById(R.id.nick);
		mPhone = (EditText) findViewById(R.id.phonenum);
		mName.addTextChangedListener(this);
		mPhone.addTextChangedListener(this);
		
		
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.back:{
			finish();
		}break;
		case R.id.commit:{
			mCommitName = mName.getText().toString();
			mCommitPhone = mPhone.getText().toString();
			mApp.showWaitting(this, null);
			
			Intent si = new Intent(this, NetService.class);
			si.setAction(NetService.ADD_NEW_DEVICE);
			si.putExtra("uid", mApp.getUID());
			si.putExtra("did", mDid);
			//si.putExtra("fid", mCommitFa.id);
			si.putExtra("devicename", mCommitName);
			
			Time t = new Time();
			t.setToNow();
			String stamp = "ADD_NEW_DEVICE" + t.toString(); 
			si.putExtra("stamp",stamp);
			mApp.addNetHandler(stamp,mHandler);
			startService(si);
		}break;
		}
	}
	
	/*private void ativateDevice(){
		Intent si = new Intent(this, NetService.class);
		si.setAction(NetService.ACTIVATE_DEVICE);
		si.putExtra("uid", mApp.getUID());
		si.putExtra("tid", mCommitTid);
		
		Time t = new Time();
		t.setToNow();
		String stamp = "ACTIVATE_DEVICE" + t.toString(); 
		si.putExtra("stamp",stamp);
		mApp.addNetHandler(stamp,mHandler);
		startService(si);
	}*/
	
	private void autoSetting(){
		Intent si = new Intent(NetService.COMMIT_DATA_ACTION);
		si.putExtra("sub_act", NetService.AUTOSET_DEVICE_MOBILENUMBER);
		si.putExtra("uid", mApp.getUID());
		si.putExtra("tid", mCommitTid);
		si.putExtra("simno", mCommitPhone);
		
		Time t = new Time();
		t.setToNow();
		String stamp = "AUTOSET_DEVICE_MOBILENUMBER" + t.toString(); 
		si.putExtra("stamp",stamp);
		mApp.addNetHandler(stamp,mHandler);
		mApp.startService(si);
	}
	
	/*private void startDeviceSetting(){
		mApp.showCustomizedDialog(this, null, 
				getResources().getString(R.string.addDevOk),
				getResources().getString(R.string.setDevicePhoto),
				getResources().getString(R.string.No),
				new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				if(v.getId() == R.id.alert_but1){
					Intent i = new Intent(NewDeviceActivity.this,DeviceManagerEdit.class);
					i.putExtra("first_set", true);
					i.putExtra("tid", mCommitTid);
					i.putExtra("phone", mCommitPhone);
					startActivity(i);
					finish();
				}else if(v.getId() == R.id.alert_but2){
					mApp.showAlertDialog(NewDeviceActivity.this, getResources().getString(R.string.notSetingHint), R.string.Yes,
							new View.OnClickListener() {	
								@Override
								public void onClick(View arg0) {
									finish();
								}
							});
				}
			}
			
		});
	}*/
	
	
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			switch(msg.what){
			case HealthApp.MSG_NET_RESPONSE:{
				Bundle b = msg.getData();
				String stamp = b.getString("stamp","ooh!No!");
				boolean canceled = b.getBoolean("canceled", false);
				if(stamp.startsWith("ADD_NEW_DEVICE")){
					String sjson = b.getString("json");
					if(sjson != null){
						try {
							JSONObject json = new JSONObject(sjson);
							int code = json.getInt("code");
							if(code == 200){
								String state = json.getString("state");
								if(state.equals("00")){
									JSONObject rec = json.getJSONObject("recdata");
									mCommitTid = rec.getString("tid");
									//ativateDevice();
									autoSetting();
									return;
								}else if(state.equals("16")){
									mApp.dismissWaiting();
									mApp.showAlertDialog(NewDeviceActivity.this, getResources().getString(R.string.addDevFailForAdminExist),
											new View.OnClickListener() {
												
												@Override
												public void onClick(View arg0) {
													finish();
												}
											});
									return;
								}
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						mApp.dismissWaiting();
						mApp.showAlertDialog(NewDeviceActivity.this, getResources().getString(R.string.addDevFail),
								new View.OnClickListener() {
									
									@Override
									public void onClick(View arg0) {
										finish();
									}
								});
					}
				}/*else if(stamp.startsWith("ACTIVATE_DEVICE")){
					String sjson = b.getString("json");
					if(sjson != null){
						try {
							JSONObject json = new JSONObject(sjson);
							int code = json.getInt("code");
							if(code == 200){
								String state = json.getString("state");
								if(state.equals("00")){
									autoSetting();
									return;
								}
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						mApp.dismissWaiting();
						mApp.showAlertDialog(NewDeviceActivity.this, getResources().getString(R.string.addDevFail),
								new View.OnClickListener() {
									
									@Override
									public void onClick(View arg0) {
										finish();
									}
								});
					}
				}*/else if(stamp.startsWith("AUTOSET_DEVICE_MOBILENUMBER")){
					String sjson = b.getString("json");
					if(sjson != null){
						mApp.dismissWaiting();
						try {
							JSONObject json = new JSONObject(sjson);
							int code = json.getInt("code");
							if(code == 200){
								String state = json.getString("state");
								if(state.equals("00")){
									mApp.getDataManager().setUserData(DataManager.F_DEVICELIST, null);
									mApp.getDataManager().refreshData(DataManager.F_DEVICELIST);
									//startDeviceSetting();
									mApp.showAlertDialog(NewDeviceActivity.this, getResources().getString(R.string.addDevOk),
											R.string.ok, new View.OnClickListener() {
												
												@Override
												public void onClick(View arg0) {
													finish();
												}
											});
									return;
								}
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						mApp.showAlertDialog(NewDeviceActivity.this, getResources().getString(R.string.addDevFail),
								new View.OnClickListener() {
									
									@Override
									public void onClick(View arg0) {
										finish();
									}
								});
					}
				}
			}break;
			
			}
		}
	};

	@Override
	public void afterTextChanged(Editable e) {
		String name = mName.getText().toString();
		String phone = mPhone.getText().toString();
		
		if((name.length() > 0) && (phone.length() > 0)){
			mCommit.setEnabled(true);
		}else{
			mCommit.setEnabled(false);
		}
	}

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub
		
	}

}
